﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.IO;
using System.Xml.Linq;
using System.Collections.Generic;
using MyDemos.Classes;
using System.Diagnostics;
using System.Threading;
using System.Windows.Threading;

namespace MyDemos.Utils
{
    public class RssReader
    {
        public delegate void CatchFinishedHandler();
        private CatchFinishedHandler QueryFinished;
        private Dispatcher mDispatcher;


        private Dictionary<String, RSSItem> RssList = new Dictionary<String, RSSItem> ();

        public Dictionary<String, RSSItem> GetResult ()
        {
            return RssList;
        }

        public RssReader (Dispatcher pDispatcher,String pUrl, CatchFinishedHandler pFinished)
        {
           // string url = "http://www.businessweekly.com.tw/feednews.php";


            mDispatcher = pDispatcher;
            QueryFinished = pFinished;
            WebRequest request = HttpWebRequest.Create (pUrl);
            IAsyncResult result = (IAsyncResult)request.BeginGetResponse (ResponseCallback, request);
        }

        private void ResponseCallback (IAsyncResult result)
        {
            int i = 0;
            try
            {
                var request = (HttpWebRequest)result.AsyncState;
                WebResponse response = request.EndGetResponse (result);

                Stream _Stream = response.GetResponseStream ();

                String _Result = Big5Util.ToUni (_Stream);


                XDocument document = XDocument.Parse (_Result);
                XElement root = document.Root.Element ("channel");

                XNode _Node = root.FirstNode;

                //List<RSSItem> _NodeList = new List<RSSItem> ();
                Dictionary<String, RSSItem> _NodeDictionary = new Dictionary<String, RSSItem> ();


                while (_Node.NextNode != null)
                {
                    i++;
                    _Node = _Node.NextNode;
                    if ((_Node as XElement).Name != "item")
                    {
                    }
                    else
                    {
                        RSSItem _Item = new RSSItem
                        {
                            Title = (_Node as XElement).Element ("title").Value,
                            Link = (_Node as XElement).Element ("link").Value,
                            Description = (_Node as XElement).Element ("description").Value,
                            Category = (_Node as XElement).Element ("category").Value,
                            Author = AuthorUtil (_Node as XElement),
                            GUID = (_Node as XElement).Element ("guid").Value,
                            PubDate = DateUtil (_Node as XElement)
                        };

                        if (i == 266)
                        {
                            var cc = _Item.PubDate;
                        }
                        if (_NodeDictionary.ContainsKey (_Item.PubDate.ToShortDateString ()))
                        {
                        }
                        else
                        {
                            _NodeDictionary.Add (_Item.PubDate.ToShortDateString (), _Item);
                        }
                    }
                }

                RssList = _NodeDictionary;
                mDispatcher.BeginInvoke (QueryFinished);
            }
            catch (Exception pException)
            {
                int q = i;
                Debug.WriteLine (pException.ToString ());
            }
        }

        String AuthorUtil (XElement pElement)
        {
            try
            {
                return pElement.Element ("author").Value;
            }
            catch (Exception)
            {
                return "";
            }
        }

        DateTime DateUtil (XElement pElement)
        {
            try
            {

                return Convert.ToDateTime (pElement.Element ("pubDate").Value);
            }
            catch (Exception)
            {
                return new DateTime ();
            }
        }

    }
}
